package com.atguigu.product.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.common.Msg;
import com.atguigu.order.OrderFeignClient;
import com.atguigu.order.bean.Order;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;

import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

/**
 *
 */
@Slf4j
@RestController
@RequestMapping("/buyGood")
@RequiredArgsConstructor
public class BuyGoodController {

    private final OrderFeignClient orderFeignClient;

    private final RocketMQTemplate rocketMQTemplate;

    @Value("${good-success-topic}")
    private String goodSuccessTopic;

    @Value("${good-timeout-topic}")
    private String goodTimeoutTopic;

    @Value("${good-sequence-topic}")
    private String goodSequenceTopic;



    /**
     * 购买商品后通过openFeign调用order服务，生成订单
     */
    @GetMapping("v1")
    public String buyGoodV1() {
        Order order = orderFeignClient.createOrder();
        return JSON.toJSONString(order);
    }

    /**
     * 在v1基础上新增需求：生成订单，同时进行购买成功提醒（rocketmq 同步）
     * rocketmq 同步消息
     */
    @GetMapping("v2")
    public String buyGoodV2() {
        Order order = orderFeignClient.createOrder();

        // 发送购买成功提醒消息
        SendResult sendResult = rocketMQTemplate.syncSend(goodSuccessTopic, JSON.toJSONString(order));
        log.info("购买成功提醒消息发送结果：{}", sendResult.getSendStatus());
        return JSON.toJSONString(order);
    }

    /**
     * 在v2基础上优化,采用异步方式（rocketmq 异步）
     * rocketmq 异步消息
     */
    @GetMapping("v3")
    public String buyGoodV3() {
        Order order = orderFeignClient.createOrder();

        // 发送购买成功提醒消息
        rocketMQTemplate.asyncSend(goodSuccessTopic, JSONUtil.toJsonStr(order), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("异步发送成功，结果：{}", sendResult.getSendStatus());
            }

            @Override
            public void onException(Throwable throwable) {
                log.info("异步发送异常，结果：{}", throwable);
            }
        });

        return JSON.toJSONString(order);
    }

    /**
     * 在v1的基础上新增需求，生成订单号，30秒内未支付，自动取消订单(同步)
     * rocketmq 延迟消息
     */
     @GetMapping("v4")
    public String buyGoodV4() {
         Order order = orderFeignClient.createOrder();

         Message message = MessageBuilder.withPayload(JSONUtil.toJsonStr(order)).build();
         // 发送一个延时消息，延迟等级为4级，也就是30s后被监听消费
         SendResult sendResult = rocketMQTemplate.syncSend(goodTimeoutTopic, message, 2000, 4);
         log.info("延时消息发送结果：{}", sendResult.getSendStatus());
         return JSON.toJSONString(order);
     }

    /**
     * 在v1的基础上新增需求，生成订单。发送下单成功提醒、物流已发货提醒、记录日志、AAA、BBB、CCC(按照顺序消费)
     * rocketmq 顺序消息
     */
    @GetMapping("v5")
    public String buyGoodV5() {
        Order order = orderFeignClient.createOrder();

        List<Msg> msgList = Arrays.asList(
                new Msg(order.getId(), "下单成功提醒"),
                new Msg(order.getId(), "物流已发货提醒"),
                new Msg(order.getId(), "记录日志"),
                new Msg(order.getId(), "AAA"),
                new Msg(order.getId(), "BBB"),
                new Msg(order.getId(), "CCC")
        );

        // 发送消息到顺序队列
        for (Msg msg : msgList) {
            rocketMQTemplate.syncSendOrderly(goodSequenceTopic, msg, String.valueOf(order.getId()));
        }

        return JSON.toJSONString(order);
    }

}

